package com.qf.efserver.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.common.core.entity.Nutrition;
import com.qf.common.core.entity.UserNutritionRecords;
import com.qf.common.core.utils.DateUtils;
import com.qf.common.core.utils.TokenUtils;
import com.qf.efserver.food.VO.FoodVO;
import com.qf.efserver.food.VO.OleFood;
import com.qf.efserver.food.mapper.NutritionFoodMapper;
import com.qf.efserver.food.mapper.UserNutritionRecordsFoodMapper;
import com.qf.efserver.food.param.UserNutritionRecordsParam;
import com.qf.efserver.food.service.FoodService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * ---今日份---
 *
 * @Author Fzl
 * @Date 2024/11/8
 * @Desc 力未尽，不言降
 */
@Service
public class FoodServiceImpl implements FoodService {

    @Resource
    private UserNutritionRecordsFoodMapper foodMapper;

    @Resource
    private NutritionFoodMapper nutritionFoodMapper;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public List<FoodVO> selectCFP() {

//        // 动态获取HttpServletRequest对象 获取当前请求的属性
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        // 从属性中获取HttpServletRequest对象
//        HttpServletRequest request = attributes.getRequest();
//        // 从请求头中获取名为"Token"的JWT令牌
//        String token = request.getHeader("Token");
//        // 使用JwtUtils类的方法解析JWT令牌
//        Claims claims = JwtUtils.parseJWT(token); // 这里打印出来是载荷对象
//        Integer uid = (Integer)claims.get("uid"); // 取出其中需要的值

        Integer uid = TokenUtils.getUidFromToken();

        //获取登录用户id
        //Integer uid = UserUtils.getUid();
        System.out.println(uid);
        //获取今天的日期
        String day = DateUtils.today();
        List<FoodVO> foodVOS = foodMapper.selectByIdAndTime(uid, day);
        if (foodVOS != null || foodVOS.size() != 0) {
            // 计算每个食物的卡路里并设置
            for (FoodVO vo : foodVOS) {
                int itemCalories = vo.getTotalCarbs() * 4
                        + vo.getTotalFat() * 9
                        + vo.getTotalProtein() * 4;
                vo.setSumCalories(itemCalories);
            }

        }

        if (foodVOS.size() == 0) {
            FoodVO foodVO = new FoodVO();
            foodVO.setSumCalories(0);
            foodVO.setTotalCarbs(0);
            foodVO.setTotalFat(0);
            foodVO.setTotalProtein(0);
            foodVO.setFoodName("");
            foodVO.setTimePeriod(0);
            foodVOS.add(foodVO);
        }
        return foodVOS;
    }


    List<Nutrition> nutritionS = null;
    @Override
    public List<Nutrition> selectShowByName(String foodName) {

        if (foodName != null){
            QueryWrapper<Nutrition> nqw = new QueryWrapper<>();
            nqw.like("food_name",foodName);
            nutritionS = nutritionFoodMapper.selectList(nqw);
            return nutritionS;

        }else {
            throw new RuntimeException("搜索为空");
        }
    }

    @Override
    public void addRecords(UserNutritionRecordsParam param) {

        Integer uid = TokenUtils.getUidFromToken();
        // 判空 如果传来的值为空 则添加失败
        if (param != null){
            // 使用线程池进行异步优化
            threadPoolExecutor.execute(()->{
                UserNutritionRecords food = new UserNutritionRecords();

                BeanUtils.copyProperties(param,food);

                food.setUserId(uid);
                food.setRecordDate(DateUtils.today());

                Map<String, Integer> timeMap = new HashMap<>();
                timeMap.put("早上", 1);
                timeMap.put("下午", 2);
                timeMap.put("晚上", 3);
                timeMap.put("任何时候",4);
                Set<String> key = timeMap.keySet(); //取出键
                boolean found = false; // 添加一个标志来检查是否找到了匹配的时间

                for (String keys : key){
                    if (param.getTimePeriod().equals(keys)){

                        food.setTimePeriod(timeMap.get(param.getTimePeriod()));

                        QueryWrapper<Nutrition> oqw = new QueryWrapper<>();

                        Nutrition nutrition = nutritionFoodMapper.selectOne(oqw.eq("food_name", param.getFoodName()));

                        food.setFoodId(nutrition.getFoodId());

                        foodMapper.insert(food);

                        found = true; // 标记为找到了匹配的时间
                        break; // 找到后退出循环
                    }
                }
                if (!found) {
                    throw new RuntimeException("请选择正确的时间：早上，下午，晚上，任何时候");
                }


            });
        }else {
            throw new RuntimeException("添加失败 数据为空");
        }
    }

    @Override
    public List<OleFood> selectOldFood() {
        // 获取id
        Integer uid = TokenUtils.getUidFromToken();

        // 查询以前吃过的食物 user_nutrition_records表 用户存储食物表
        List<UserNutritionRecords> userNutritionRecords = foodMapper.selectList(new LambdaQueryWrapper<UserNutritionRecords>()
                .eq(UserNutritionRecords::getUserId, uid)
                .lt(UserNutritionRecords::getRecordDate, LocalDate.now()
                ));

        // 查询以前吃过的食物最终
        List<OleFood> oleFoods = userNutritionRecords.stream().map(record -> {
            // 查询以前吃过的食物名称 通过id查询
            Nutrition nutrition = nutritionFoodMapper.selectById(record.getFoodId());
            // 计算每个食物的卡路里并设置
            Integer quantity = record.getQuantity(); // 单个食物吃了多少
            Integer calories = nutrition.getCalories(); // 每一百克食物的卡路里
            Integer calorie = quantity * calories / 100; // 计算

            return new OleFood(
                    nutrition.getFoodName(),
                    record.getQuantity(),
                    calorie
            );
        }).collect(Collectors.toList());



        return oleFoods;
    }

}
